# __author__ = 'heyin'
# __date__ = '2018/10/24 8:58'
from sklearn.linear_model import LinearRegression
from sklearn.linear_model.stochastic_gradient import SGDRegressor
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error


def myliner():
    # 获取boston房价数据
    boston = load_boston()
    # 获取特征值目标值数据
    x = boston.data
    y = boston.target
    # print(x)
    # print(y)
    # print(boston.feature_names)

    # 分割数据集
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)

    # 因为牵涉到乘法和平方运算（求损失函数），因此需要对特征进行标准化处理
    sd_x = StandardScaler()
    # 特征值和目标值均要进行标准化，目标值不进行标准化，求得的w权重值就会很大，因为特征值很小
    x_train = sd_x.fit_transform(x_train)
    x_test = sd_x.transform(x_test)

    sd_y = StandardScaler()
    y_train = sd_y.fit_transform(y_train.reshape(-1, 1))
    # y_test = sd_y.transform(y_test.reshape(-1, 1))

    # 进行估计器的运算
    # 正规方程
    # lr = LinearRegression()
    # lr.fit(x_train, y_train)
    # # 预测房子价格要的是真实价格，因此需要将数据逆转
    # y_prelr = lr.predict(x_test)
    # print(sd_y.inverse_transform(y_prelr))
    # print(lr.coef_)
    # # 均方误差评判效果
    # mse = mean_squared_error(y_test, sd_y.inverse_transform(y_prelr))
    # print(mse)

    # 梯度下降
    # 运行过程中出现警告的解决方法：https://blog.csdn.net/llx1026/article/details/77940880
    sgd = SGDRegressor(max_iter=5)
    sgd.fit(x_train, y_train.ravel())
    y_presgd = sgd.predict(x_test)
    print('sgd真实价格：', sd_y.inverse_transform(y_presgd))
    msesgd = mean_squared_error(y_test, sd_y.inverse_transform(y_presgd))
    print('均方误差sgd', msesgd)



if __name__ == '__main__':
    myliner()
